'use strict';

const Controller = require('egg').Controller;
const { ObjectId } = require('mongodb')
class CollectController extends Controller {
    async index() {
        const { ctx } = this;
        // console.log(ctx.request.body);
        var { id, collect } = ctx.request.body;
        var db = this.app.mongodb;
        await db.collection("strategy").updateOne({ _id: ObjectId(id) }, { $set: { collect: collect } })
        var res = await ctx.service.trip.find(id)
        // console.log(res[0]);
        try {
            if (collect) {
                await db.collection("tripCollect").insertOne(res[0]);
                ctx.body = {
                    status: 200,
                    msg: "收藏成功"
                }
            } else {
                await db.collection("tripCollect").deleteOne({ _id: ObjectId(id) });
                ctx.body = {
                    status: 400,
                    msg: "取消收藏"
                }
            }
        } catch (err) {
            this.app.logger.error(err)
            ctx.body = {
                status: 400,
                msg: "数据已经存在"
            }
        }
    }
}

module.exports = CollectController;
